package com.xinzhitong.www.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinzhitong.www.exception.*;
import com.xinzhitong.www.exception.comment.CommentInsertErrException;
import com.xinzhitong.www.exception.coursecommentreturn.NoCourseCommentException;
import com.xinzhitong.www.exception.coursegeneral.IdNoCourseException;
import com.xinzhitong.www.exception.courseintroduction.IdNoIntroductionException;
import com.xinzhitong.www.exception.coursemessage.NoCourseMessage;
import com.xinzhitong.www.exception.courseprice.NoPriceException;
import com.xinzhitong.www.exception.coursewatched.ClassIdErrException;
import com.xinzhitong.www.exception.coursewatched.CourseWatchedInsertErrException;
import com.xinzhitong.www.exception.coursewatchedselect.CourseWatchedNullException;
import com.xinzhitong.www.exception.video.NoVideoException;
import com.xinzhitong.www.mapper.CourseMapper;
import com.xinzhitong.www.pojo.Chapter;
import com.xinzhitong.www.pojo.Comment;
import com.xinzhitong.www.pojo.Course;
import com.xinzhitong.www.pojo.User;
import com.xinzhitong.www.service.CourseService;
import com.xinzhitong.www.utils.FileHelper;
import com.xinzhitong.www.utils.MyPageInfo;
import com.xinzhitong.www.utils.SearchKeyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 课程模块实现类
 *
 * @author 钟伟良 吴展鹏
 */
@Service
@Transactional
public class CourseServiceImpl implements CourseService {
    @Resource
    private CourseMapper courseMapper;


    @Override
    public double price(Integer id) throws NoPriceException {

        Double z = courseMapper.SelectPriceById(id);
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String x = user.getUsername();
        List<Map<String, Object>> temp = courseMapper.selectCourseMine(x);
        for (int i = 0; i < temp.size(); i++) {
            int a=(int)temp.get(i).get("courseId");
            if(a==id) {
                z = -1.0;
            }

        }
        if (z == null)
            throw new NoPriceException();
        else
            return z;
    }

    @Override
    public void InsertACourse(
            Integer credentialId,
            String  courseName,
            String  courseIntro,
            Integer price,
            String  teacher,
            String  teacherIntro,
            String  forward,
            String  forPost,
            MultipartFile picture
    ){
        if (courseMapper.insertAGood()==0){
            throw new BusyException();
        }
        Integer id = courseMapper.selectLastId();
        String coursePath = "/static/course" + "/" + id + "/" + "picture.jpg";
        try {
            FileHelper.saveTo(coursePath, picture);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusyException();
        }
        if (courseMapper.insertACourse(
                id,
                credentialId,
                courseName,
                courseIntro,
                price,
                teacher,
                teacherIntro,
                forward,
                forPost,
                coursePath
        )==0){
            throw new BusyException();
        }
    }

    @Override
    public void deleteCourse(  List<Integer> idList){
        for(Integer id:idList)
        {
            courseMapper.deleteCourse(id);
            courseMapper.deleteGoodId(id);
        }
    }

    @Override
    public MyPageInfo getCourseGeneral(String name, String word, Integer pageNo, Integer pageSize)
            throws ConsignGeneralException {
        PageHelper.startPage(pageNo, pageSize);
        String word1 = SearchKeyUtil.makeKey(word);
        String name1 = SearchKeyUtil.makeKey(name);

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //List<Map<String, Object>> x = consignMapper.selectConsignGeneral(name1, state1, user.getUsername());
        List<Map<String, Object>> x= courseMapper.SearchCourseGeneral(name1, word1);
        //if (x.size() == 0)
            //throw new NoConsignGeneralException();

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(x);
//        for (Map<String, Object> temp : pageInfo.getList()) {
//            if (temp.get("publishTime") == null)
//                temp.put("publishTime", null);
//            else
//                temp.replace("publishTime", temp.get("publishTime").toString());
//        }
        return new MyPageInfo(pageInfo);
    }

    @Override
    public List<Map<String,Object>> getACourseInfo (Integer id){
        return courseMapper.getACourseInfo(id);
    }

    @Override
    public void EditACourse(
            Integer id,
            Integer credentialId,
            String  courseName,
            String  courseIntro,
            Integer price,
            String  teacher,
            String  teacherIntro,
            String  forward,
            String  forPost,
            MultipartFile picture
     ){
        String coursePath = "/static/course" + "/" + id + "/" + "picture.jpg";
        try {
            FileHelper.saveTo(coursePath, picture);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusyException();
        }
       courseMapper.editACourse(
                id,
                credentialId,
                courseName,
                courseIntro,
                price,
                teacher,
                teacherIntro,
                forward,
                forPost,
                coursePath
        );

    }

    @Override
    public String video(Integer id) throws VideoException {

        String temp = courseMapper.SelectVideoById(id);
        if (temp == null)
            throw new NoVideoException();
        else
            return FileHelper.fileURL + temp;
    }


    @Override
    public List<Map<String, Object>> catalogue(Integer id) {
        List<Chapter> x = courseMapper.selectNameNo(id);
        int y = x.size();
        List<Map<String, Object>> last = new ArrayList<Map<String, Object>>();//总目录列表
        for (Chapter z : x) {
            int no = z.getNo();
            String name = z.getName(); //章节名
            List<Map<String, Object>> cls = null;
            cls = courseMapper.selectIdName(no, id);//章节下的视频名和视频id

            Map<String, Object> yyy = new HashMap<>();
            yyy.put("classNameAndIdAndNo", cls);
            Map<String, Object> xxx = new HashMap<>();
            xxx.put("no", no);
            xxx.put("chapterName", name);
            xxx.put("chapterContent", yyy);
            last.add(xxx);
            last.sort(Comparator.comparingInt(o -> (int) o.get("no")));
        }
        return last;

    }


    @Override
    public Map<String, Object> introduction(Integer id) throws IdNoIntroductionException {
        Course cls = null;
        cls = courseMapper.selectIntroduction(id);
        if (cls == null)
            throw new IdNoIntroductionException();
        Map<String, Object> yyy = new HashMap<>();
        yyy.put("title", cls.getName());
        yyy.put("content", cls);
        return yyy;
    }

    @Override
    public List<Map<String, Object>> courseGeneral(Integer id) throws IdNoCourseException {
        List<Map<String, Object>> x = courseMapper.selectCourseGeneral(id);
        if (x.size() == 0)
            throw new IdNoCourseException();
        for (Map<String, Object> tmp : x) {
            String nts = tmp.get("number").toString();
            String pts = tmp.get("price").toString();
            tmp.remove("number");
            tmp.remove("price");
            tmp.put("number",nts);
            tmp.put("price",pts);
            tmp.put("picture", FileHelper.fileURL + tmp.get("picture"));
        }
        return x;
    }

    @Override
    public List<Map<String, Object>> courseMine() throws CourseMineNullException {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String x = user.getUsername();
        List<Map<String, Object>> temp = courseMapper.selectCourseMine(x);
        if (temp.size() == 0) {
            throw new CourseMineNullException();
        } else
            for (Map<String, Object> tmp : temp) {
                tmp.put("picture", FileHelper.fileURL + tmp.get("picture"));
            }
        return temp;
    }

    @Override
    public String videoLink(Integer id) throws CourseVideoLinkException {

        String x = courseMapper.selectVideoLink(id);
        if (x == null)
            throw new CourseVideoLinkException();
        else
            return FileHelper.fileURL + x;

    }

    @Override
    public void comment(Integer courseId, String text) throws CommentInsertErrException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String x = user.getUsername();
        Integer y = courseMapper.insertCourseComment(x, courseId, text);
        if (y != 1) throw new CommentInsertErrException();
    }

    @Override
    public List<Comment> returnComment(Integer id) throws NoCourseCommentException {
        List<Comment> temp = courseMapper.selectComment(id);
        if (temp.size() == 0)
            throw new NoCourseCommentException();
        else
            return temp;
    }

    @Override
    public void watched(Integer classId) throws CourseWatchedException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String x = user.getUsername();
        Integer s = courseMapper.selectClassId(classId);
        if (s == null)
            throw new ClassIdErrException();
        Integer y = courseMapper.insertUserWatched(x, classId);
        if (y != 1) throw new CourseWatchedInsertErrException();
    }

    @Override
    public Integer watchedReturn(Integer courseId) throws CourseWatchedSelectException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String x = user.getUsername();
        Integer y = courseMapper.selectUserWhatched(x, courseId);
        if (y == 0) throw new CourseWatchedNullException();
        else return y;
    }

    @Override
    public Map<String, Object> getMessage(Integer id) throws CourseMessageException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Map<String, Object> x = courseMapper.selectCourseMessage(user.getUsername(), id);
        if (x == null)
            throw new NoCourseMessage();
        x.put("date", x.get("date").toString());
        return x;
    }


}
